<template>
  <div class="boder-div-box">
    <div class="dialog-container">
      <div class="left-box">
        <!-- 方案名称输入 -->
        <div class="plan-name-box">
          <span class="plan-font">方案名称</span>
          <el-input v-model="state.schemeName" placeholder="请输入方案名称" :disabled="true" />
        </div>
        <!-- tabs -->
        <div class="tabs-box">
          <!-- <el-tabs v-model="state.leftActiveName" class="demo-tabs" stretch>
            <el-tab-pane label="单库" name="first"> -->
          <!-- 水库类型选择框 -->

          <el-tabs
            v-model="state.warehouseType"
            class="demo-tabs demo-tabs1"
            type="border-card"
            stretch
          >
            <el-tab-pane label="水库" name="first">
              <div class="first-input">
                <!-- <el-input v-model="input" /> -->
                <el-input v-model="state.waterValue" class="input-with-select" placeholder="水库">
                  <template #prepend>
                    <el-select
                      v-model="state.reservoirDispachType"
                      placeholder="全部/单工程/联合"
                      @change="handleChangeDistype"
                    >
                      <el-option label="全部" :value="2" />
                      <el-option label="单工程" :value="0" />
                      <el-option label="联合" :value="1" />
                    </el-select>
                  </template>
                  <template #append>
                    <el-button @click="handleSearchReservoir">
                      <el-icon>
                        <Search />
                      </el-icon>
                    </el-button>
                  </template>
                </el-input>
              </div>
              <div class="first-table">
                <el-table
                  ref="tableDataRef"
                  class="single-table"
                  :data="state.singleTableData"
                  :span-method="objectSpanMethod"
                  highlight-current-row
                  border
                  style="width: 100%"
                  :row-style="cellStyle"
                  :row-class-name="tableRowClassName"
                  :cell-class-name="tableCellClassName"
                  @filter-change="filterHandler"
                  @row-click="handleCurrentChangeSingle"
                  @selection-change="handleSelectionChangeSingle"
                >
                  <el-table-column
                    prop="rangeName"
                    label="区域名称"
                    align="center"
                    show-overflow-tooltip
                  >
                    <template #default="{ row }">
                      <div @click.stop="handleCellClick(row)">
                        <div class="icon">
                          <i
                            :class="[
                              'iconfont',
                              row.engType == 1 && row.rangeName == state.currentIndex
                                ? 'active'
                                : ''
                            ]"
                            >&#xe62a;</i
                          >
                        </div>
                        <div
                          :class="[
                            'engType-name',
                            row.engType == 1 && row.rangeName == state.currentIndex ? 'active' : ''
                          ]"
                        >
                          {{ row.rangeName }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="engTypeName"
                    label="单/联"
                    align="center"
                    show-overflow-tooltip
                  >
                    <template #default="{ row }">
                      <div :class="['engType-name-two', row.engType == 1 ? 'joint' : '']">
                        {{ row.engTypeName }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="sttpName"
                    label="类型"
                    align="center"
                    show-overflow-tooltip
                  />
                  <el-table-column prop="blknm" label="名称" align="center" show-overflow-tooltip />
                  <el-table-column
                    prop="disType"
                    label="调度方式"
                    align="center"
                    show-overflow-tooltip
                    :filters="[
                      { text: '规程调度', value: '规程调度' },
                      { text: '优化调度', value: '优化调度' },
                      { text: '指令调度', value: '指令调度' },
                      { text: '不拦蓄', value: '不拦蓄' },
                      { text: '蓄水', value: '蓄水' },
                      { text: '维持现状出流', value: '维持现状出流' }
                    ]"
                    :filter-multiple="false"
                  >
                    <template #default="{ row }">
                      {{ switchDispatchMethods(row.disType) }}
                    </template>
                  </el-table-column>
                </el-table>
                <!-- </div> -->
              </div>
              <div class="first-select">
                <span class="plan-font1">默认调度方式</span>
                <el-select
                  v-model="state.diapatchMethods"
                  placeholder=""
                  @change="handleChangeSelect"
                >
                  <el-option
                    :key="index"
                    v-for="(item, index) in state.modelType"
                    :value="item.id"
                    :label="item.label"
                  />
                </el-select>
                <!-- <el-switch class="switch-right" v-model="state.value1" /> -->
              </div>
              <!-- <div class="first-bottom-btn">
                <el-button type="success" @click="handleConfigJoint">设置联合调度</el-button>
                <el-button type="primary" @click="handleSave">方案保存</el-button>
              </div> -->
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="right-box">
        <!-- 水库信息 -->
        <div class="reservoir-info">
          <!-- 水库名称 -->
          <div class="reservoir-name">{{ state.currentName }}</div>
          <div class="info-body">
            <div class="left-info">
              <leftInfo
                ref="leftInfoRef"
                @emitSaveItem="emitSaveItem"
                @emitTryScheme="emitTryScheme"
                @emitTryJoinScheme="emitTryJoinScheme"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <showDetails ref="showDetailsRef" />'
    <!-- 联合试算详情弹框 -->
    <jointResult ref="jointResultRef" />
    <!-- 配置联合调度 -->
    <joint ref="jointRef" @handleSaveJoint="handleSaveJoint" />
  </div>
</template>

<script setup>
import { ref, reactive, defineExpose, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import leftInfo from './cpns/leftInfo/index.vue'
import showDetails from './cpns/showDetails/index.vue'
import jointResult from './cpns/jointResult/index.vue'
import joint from './cpns/joint/index.vue'
import {
  getResvs,
  regsSchemesAll,
  optimSchemesAll,
  getJointResvs,
  getRegsSchemes,
  getOptimSchemes,
  addManualDispatchScheme,
  getResvCond,
  getRegsRules,
  addDispatchScheme,
  editDispatchScheme,
  dispatchDetail,
  saveDispatchScheme,
  getDispatchSchemeDetail,
  deleteTrialScheme,
  trialCalculate,
  jointTrialCalculate,
  trialResult,
  saveTrialScheme,
  resvDispatchDetail,
  //
  getResvConds,
  //查看调度水库信息
  getDisResvs,
  saveTrialJointScheme,
  getJointTrialEig,
  getJointTrialInfo,
  getRangeParams,
  //删除联合试算
  deleteJointTrialScheme
} from '@/services/modules/dispatch-manage'
//概画图

const state = reactive({
  trialFlag: false,
  setInterValTimer: null,
  jointTrialIds: [],
  jointTrialIdArr: [],
  jointSsList: [],
  jointTrialData: [],
  showGoint: false,
  jointCode: '',
  currentName: '',
  currentIndex: '',
  scidIns: '',
  dataItem: {},

  reservoirDispachType: '',
  deleteTrialIds: [],
  resultData: [],
  trialIdArr: [],
  trialIds: [],
  dispatchSchemeData: [],
  modelInfo: [],
  trialData: [],
  saveForm: {},
  formCalcScid: '',
  formModel: '',
  parentModel: '',
  diapatchMethods: '',
  schemeName: '',
  zoneId: '1',
  title: '--',
  waterValue: '',
  blkcd: '',
  baseCondArr: [],
  rowItem: {},
  //单库
  singleTableData: [],
  //
  regsSchemesAllData: [],
  // 左侧tabs
  // leftActiveName: "first",
  // 水库类型
  warehouseType: 'first',
  // 底部switch
  value1: false,
  // 选中的试算列表
  ssList: [],
  rangeCode: ''
  // radioModel: "1",
})
const jointRef = ref(null)
const jointResultRef = ref(null)
const table = ref(null)
const jointTable = ref(null)
const leftInfoRef = ref(null)
const showDetailsRef = ref(null)
const tableDataRef = ref(null)
const emit = defineEmits(['closeForm'])

const props = defineProps({
  itemRow: Object,
  default: () => {}
})
watch(
  () => {
    props.itemRow
  },
  () => {
    handleOpenModal(props.itemRow)
  },
  {
    immediate: true,
    deep: true
  }
)
//确认
function handleSure(index, row) {
  getJointTrialInfo({ zoneId: state.zoneId, trialId: row.id }).then((res) => {
    if (res.code === 200) {
      state.saveForm.joints.forEach((item) => {
        res.data.joints.forEach((e) => {
          if (item.rangeCode == e.optim.val[0].rangeCode) {
            item = { ...e, jointTrialData: item.jointTrialData }
          }
        })
      })
      state.saveForm.reservoirs = res.data.reservoirs
      ElMessage.success('保存成功')
    }
  })
}
// 根据水库名称 调度类型,搜索水库
async function handleSearchReservoir() {
  await handleChangeSelect(state.modelType[0].id, state.jointCode)
  state.singleTableData = state.singleTableData.filter((item) => {
    return item.blknm.includes(state.waterValue)
  })
}
// 选择调度方式
async function handleChangeDistype(val) {
  await handleChangeSelect(state.modelType[0].id, state.jointCode)
  state.singleTableData = state.singleTableData.filter((item) => {
    switch (state.reservoirDispachType) {
      case 0:
        return item.engType == 0

      case 1:
        return item.engType == 1
      case 2:
        return item.engType == 0 || item.engType == 1

      default:
        break
    }
    return
  })
}

//多选单库试算方案
function handleSelectionTry(arr) {
  // 选中的试算列表
  state.ssList = arr
  console.log(arr, '多选试算')
  state.trialIdArr = []
  if (arr.length) {
    arr.forEach((e) => {
      state.trialIdArr.push(e.trialId)
    })
  }
  state.trialIdArr = [...new Set(state.trialIdArr)]
}
//多选联合试算方案
function handleSelectionJointTry(arr) {
  // 选中的试算列表
  state.jointSsList = arr
  console.log(arr, '多选试算')
  state.jointTrialIdArr = []
  if (arr.length) {
    arr.forEach((e) => {
      state.jointTrialIdArr.push(e.id)
    })
  }
  state.jointTrialIdArr = [...new Set(state.jointTrialIdArr)]
}
function tableRowClassName({ row, column, rowIndex, columnIndex }) {
  //逻辑判断决定是否修改样式，如果分组一致则使用同一个样式
  if (row.rangeName == state.currentIndex) {
    console.log(row, column, rowIndex, columnIndex, '123')
    return 'row-bg'
  } else {
    return ''
  }
}
function tableCellClassName({ row, column, rowIndex, columnIndex }) {
  if (row.rangeName == state.currentIndex) {
    if (column.label == '区域名称') {
      return 'cell-bg'
    }
  } else {
    return 'cell-bg'
  }
}
/**
 * 点击单元格
 */
const handleCellClick = (row) => {
  state.trialFlag = false
  clearInterval(state.setInterValTimer)
  //标记当前是哪个分组
  state.currentIndex = row.rangeName
  if (row.engType == 1) {
    state.currentName = row.rangeName
    tableDataRef.value.setCurrentRow(-1)
    // handleCurrentChangeSingle(-1,row.rangeCode)
    state.showGoint = true
    leftInfoRef.value.handleClickModel({
      blkcd: state.blkcd,
      blknm: state.blknm,
      singleData: state.singleTableData,
      parentId: state.parentId,
      scid: state.dispatchSchemeData.length && state.dispatchSchemeData[0].scid,
      waterId: state.zoneId,
      scidIns: state.scidIns,
      showGoint: state.showGoint,
      joints: state.saveForm.joints,
      rangeCode: row.rangeCode
    })
    let arr = state.saveForm.joints.filter((e) => {
      return e.rangeCode == row.rangeCode
    })
    state.jointTrialData = arr[0]?.jointTrialData
  }
}
/**
 * 试算列表结果数据合并
 * arr 计算结果集合
 */
const trialDataFliter = (arr) => {
  state.trialData.forEach((item, index) => {
    arr.forEach((child, childIndex) => {
      if (item.trialName == child.trialName) {
        state.trialData.splice(index, 1, { ...item, ...child })
      }
    })
  })
}
//点击试算
function handleClickTryComput() {
  if (state.trialIdArr.length <= 0) {
    ElMessage.warning('请选择试算方案')
    return false
  }
  trialCalculate({ trialIds: state.trialIdArr.join() }).then((res) => {
    if (res.code === 200) {
      trialResult({ trialIds: state.trialIdArr.join() }).then((res) => {
        if (res.code === 200) {
          state.resultData.push(...res.data)
          trialDataFliter(state.resultData)
        }
      })
    }
  })
}
//试算联合
function handleClickTryComputJoint() {
  if (state.jointTrialIdArr.length <= 0) {
    ElMessage.warning('请选择联合试算方案')
    return false
  }
  state.trialFlag = true
  clearInterval(state.setInterValTimer)
  jointTrialCalculate({ trialIds: state.jointTrialIdArr.join() }).then((res) => {
    if (res.code === 200) {
      // trialResult({ trialIds: state.trialIdArr.join() }).then((res) => {
      //   if (res.code === 200) {
      //     state.resultData.push(...res.data)
      //     trialDataFliter(state.resultData)
      //   }
      // })
    }
  })
  state.setInterValTimer = setInterval(async () => {
    let arr = state.jointTrialIdArr
    await getJointTrialEigList(state.jointTrialIds.join(','), state.rangeCode)
    state.jointTrialData.forEach((item) => {
      if (arr.includes(item.id)) {
        jointTable.value.toggleRowSelection(item, true)
      }
    })
    console.log('999999', state.jointSsList)
  }, 3000)
}
//
const filterData = (arr) => {
  arr.forEach((item) => {
    state.saveForm.reservoirs.push({
      ins: {},
      blkcd: item.blkcd,
      disType: item.disType,
      disMid: item.models[0].mid,
      disScid: item.models[0].schemes[0].id,
      optims: item.models[0].schemes[0].optims,

      rules: (item.models[0].schemes[0].rules =
        item.models[0].schemes[0].rules &&
        item.models[0].schemes[0].rules.map((child) => {
          let { id, ...obj } = child
          return { ...obj }
        })),
      conds: (item.models[0].schemes[0].conds =
        item.models[0].schemes[0].conds &&
        item.models[0].schemes[0].conds.map((child) => {
          let { id, ...obj } = child
          return { ...obj }
        })),

      trials: [],
      trialData: []
    })
  })
}
// 水库右上角 选择调度方式
const filterHandler = async (val, row, column) => {
  let name = val[Object.keys(val)[0]][0]
  state.saveForm.reservoirs = []
  switch (name) {
    case '规程调度':
      regsSchemesAll({ blkcd: '', zoneId: state.zoneId }).then(async (res) => {
        if (res.code === 200) {
          state.regsSchemesAllData = res.data
          console.log('123', res.data, state.singleTableData)
          let arr1 = state.regsSchemesAllData
          let arr2 = state.singleTableData
          for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
              if (arr1[i].blkcd === arr2[j].blkcd) {
                arr2[j].models = arr1[i].models
                arr2[j].disType = 1
              }
            }
          }
          state.singleTableData = arr2
          filterData(state.singleTableData)
          await getResvCondsList(state.scidIns)
          // 选择第一个水库
          handleCurrentChangeSingle(state.singleTableData[0], 0)
          tableDataRef.value.setCurrentRow(state.singleTableData[0])
        }
      })
      break
    case '优化调度':
      optimSchemesAll({ blkcd: '', zoneId: state.zoneId }).then(async (res) => {
        if (res.code === 200) {
          state.regsSchemesAllData = res.data
          console.log('123', res.data, state.singleTableData)
          let arr1 = state.regsSchemesAllData
          let arr2 = state.singleTableData
          for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
              if (arr1[i].blkcd === arr2[j].blkcd) {
                arr2[j].models = arr1[i].models
                arr2[j].disType = 2
              }
            }
          }
          state.singleTableData = arr2
          filterData(state.singleTableData)
          await getResvCondsList(state.scidIns)
          handleCurrentChangeSingle(state.singleTableData[0], 0)
          tableDataRef.value.setCurrentRow(state.singleTableData[0])
        }
      })
      break
    case '指令调度':
      state.singleTableData = state.singleTableData.map((item) => {
        return { ...item, disType: 3 }
      })
      filterData(state.singleTableData)
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])

      break
    case '不拦蓄':
      state.singleTableData = state.singleTableData.map((item) => {
        return { ...item, disType: 4 }
      })
      filterData(state.singleTableData)
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])
      break
    case '蓄水':
      state.singleTableData = state.singleTableData.map((item) => {
        return { ...item, disType: 5 }
      })
      filterData(state.singleTableData)
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])
      break
    case '维持现状出流':
      state.singleTableData = state.singleTableData.map((item) => {
        return { ...item, disType: 6 }
      })
      filterData(state.singleTableData)
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])
      break

    default:
      break
  }

  // return switchDispatchMethods(row[property]) === value
  //  return true
}

//设置联合调度
function handleConfigJoint() {
  if (state.dispatchSchemeData[0].calcscType != '流域方案') {
    ElMessage.warning('来水方案不是全流域方案，无法设置联合调度,请重新选择!')
    return false
  }
  jointRef.value.handleOpenModal({ zoneId: state.zoneId })
}
// 保存
function handleSave() {
  state.saveForm.scName = state.schemeName
  if (state.saveForm.scName) {
    state.saveForm.disTypes = state.diapatchMethods
    state.saveForm.basisId = state.dispatchSchemeData[0].scid
    saveDispatchScheme(state.saveForm).then((res) => {
      if (res.code == 200) {
        emit('closeForm')
      }
    })
  } else {
    ElMessage.warning('请输入方案名称')
  }

  console.log('666', state.saveForm)
}
// 点击确认回调
function emitSaveItem(item) {
  if (state.showGoint) {
    if (state.saveForm.joints?.length) {
      state.saveForm.joints.forEach((i, index) => {
        if (i.rangeCode == item.rangeCode) {
          state.saveForm.joints.splice(index, 1, item.joint)
        }
      })
    }
    ElMessage.success('联合参数保存成功')
    // debugger
    // state.saveForm.joints
  } else {
    state.saveForm.reservoirs.forEach((child, index) => {
      if (child.blkcd == item.blkcd) {
        item.trials = state.saveForm.reservoirs[index]?.trials
        state.saveForm.reservoirs.splice(index, 1, item)
      }
    })
    state.singleTableData.forEach((e) => {
      if (e.blkcd == item.blkcd) {
        e.disType = item.disType
        // 优化
        e.models[0].schemes[0].optims = item.optims
        e.models[0].schemes[0].rules = item.rules
        e.models[0].schemes[0].ins = item.ins
        // 基本条件
        e.models[0].schemes[0].conds = item.conds
        e.models[0].schemes[0].precipitations = item.precipitations
      }
    })
    ElMessage.success('单库参数保存成功')
  }
}
// 点击参与试算回调
function emitTryScheme(item) {
  console.log('试算名称', item)
  state.singleTableData.forEach((child, index) => {
    if (child.blkcd == item.paramsItem.blkcd) {
      saveTrialScheme({
        ...item.paramsItem,
        trialName: `${item.paramsItem.trialName}${child.trialData.length}`
      }).then((res) => {
        if (res.code == 200) {
          // 两次push分别是 列表数据和要传入后端的数据
          child.trialData.push({
            ...item.paramsItem,
            trialName: `${item.paramsItem.trialName}${child.trialData.length}`,
            trialId: res.data.trialId
          })
          console.log(child.trialData, '试算值')
          state.saveForm.reservoirs.forEach((child, index) => {
            if (child.blkcd == item.paramsItem.blkcd) {
              child.trials.push({ trialId: res.data.trialId })
              state.deleteTrialIds.push({ trialId: res.data.trialId })
            }
          })
          state.dataItem = child
          state.trialData = state.dataItem.trialData
          table.value.toggleAllSelection()
        }
      })
    }
  })
}
//
function getJointTrialEigList(ids, rangeCode) {
  return new Promise((resolve, reject) => {
    getJointTrialEig({ trialIds: ids }).then((res) => {
      if (res.code === 200) {
        state.saveForm.joints.forEach((el, index) => {
          if (el.rangeCode == rangeCode) {
            let arr = []
            arr = res.data.filter((i) => {
              return i.rangeCode == rangeCode
            })
            el.jointTrialData = arr
            state.jointTrialData = arr
            let num = state.jointSsList.every((name) => {
              return name.status == 2 || name.status == 3
            })
            if (num) {
              state.trialFlag = false
              clearInterval(state.setInterValTimer)
            }
          }
        })
        resolve(res.data)
      }
    })
  })
}
//保存联合试算
function emitTryJoinScheme(item) {
  state.rangeCode = item.rangeCode
  saveTrialJointScheme({
    reservoirs: state.saveForm.reservoirs,
    ...item,
    joints: state.saveForm.joints,
    trialName: `${state.currentName}试算方案${state.jointTrialIds.length}`
  }).then(async (res) => {
    if (res.code === 200) {
      state.jointTrialIds.push(res.data.trialId)
      await getJointTrialEigList(state.jointTrialIds.join(','), item.rangeCode)
      jointTable.value.toggleAllSelection()
    }
  })

  // if (state.saveForm.joints?.length) {
  //   state.saveForm.joints.forEach((e, i) => {
  //     if (e.rangeCode == item.rangeCode) {

  //     }
  //   })
  // } else {
  //   ElMessage.warning('请先保存参数')
  //   return false
  // }
}
//
async function handleSaveJoint(item) {
  state.jointTrialIds = []
  state.jointCode = item
  state.saveForm.joints = []
  state.jointCode.split(',').forEach((e) => {
    getRangeParams({ scid: state.dispatchSchemeData[0].scid, rangeCode: e }).then((res) => {
      if (res.code === 200) {
        state.saveForm.joints.push({ ...res.data, rangeCode: e, jointTrialData: [] })
      }
    })
  })
  await handleChangeSelect(state.diapatchMethods, item)
  await getResvCondsList(state.scidIns)
  handleCurrentChangeSingle(state.singleTableData[0], 0)
  tableDataRef.value.setCurrentRow(state.singleTableData[0])
}
// 获取水库列表后由默认调度方式拼接调度方式至水库列表
function handleChangeSelect(val, childItem) {
  state.saveForm.reservoirs = []
  state.modelInfo.forEach((e) => {
    if (e.disType == val) {
      state.scidIns = e.scid
    }
  })
  // 查询水库信息
  ResvsList(state.zoneId, childItem)
  return new Promise(async (resolve, reject) => {
    if (val == 1) {
      regsSchemesAll({ blkcd: '', zoneId: state.zoneId }).then(async (res) => {
        if (res.code === 200) {
          state.regsSchemesAllData = res.data
          console.log('123', res.data, state.singleTableData)
          let arr1 = state.regsSchemesAllData
          let arr2 = state.singleTableData
          for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
              if (arr1[i].blkcd === arr2[j].blkcd) {
                arr2[j].models = arr1[i].models
                arr2[j].disType = 1
                console.log('888')
              }
            }
          }

          state.singleTableData = arr2
          filterData(state.singleTableData)
          await getResvCondsList(state.scidIns)
          handleCurrentChangeSingle(state.singleTableData[0], 0)
          tableDataRef.value.setCurrentRow(state.singleTableData[0])
          resolve(state.singleTableData)
        }
      })
    } else {
      state.singleTableData = state.singleTableData.map((item) => {
        return { ...item, disType: val }
      })
      resolve(state.singleTableData)
      filterData(state.singleTableData)
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])
    }
    console.log('11', state.modelInfo, val, state.parentModel)
    state.dispatchSchemeData = state.modelInfo.filter((item) => {
      return item.disType == val && item.model == state.parentModel
    })
    state.saveForm.model = state.dispatchSchemeData[0]?.model
    state.saveForm.calcScid = state.dispatchSchemeData[0]?.calcScid
  })
}
// 列表中调度方式转换
function switchDispatchMethods(disType) {
  switch (disType) {
    case 1:
      return '规程调度'
    case 2:
      return '优化调度'
    case 3:
      return '指令调度'
    case 4:
      return '不拦蓄'
    case 5:
      return '蓄水'
    case 6:
      return '维持现状出流'

    default:
      break
  }
}
//逻辑删除试算方案
function handleDeleteTryScheme(index, item) {
  deleteTrialScheme({ ids: item.id, delType: 0 }).then((res) => {
    if (res.code === 200) {
      console.log('123')
    }
  })
  state.trialData.splice(index, 1)
  table.value.toggleAllSelection()
}
//逻辑删除联合试算方案
function handleDeleteTryJointScheme(index, item) {
  deleteJointTrialScheme({ ids: item.id, delType: 0 }).then((res) => {
    if (res.code === 200) {
      state.jointTrialIds = state.jointTrialIds.filter((e) => {
        return item.id != e
      })
    }
  })
  state.jointTrialData.splice(index, 1)
  jointTable.value.toggleAllSelection()
}
// 打开弹框
async function handleOpenModal(item) {
  state.schemeName = ''

  // state.title = item.parentScheme[0].scName
  state.zoneId = item.watershedId

  // 父方案id
  state.parentId = item.parentScheme[0]?.id
  state.parentModel = item.model
  state.saveForm = {
    ddfs: 1,
    parentId: state.parentId,
    scName: state.schemeName,
    model: state.formModel,
    calcScid: state.formCalcScid,
    reservoirs: [],
    disTypes: state.diapatchMethods,
    joints: []
  }
  // 查询父级方案详情
  await getDispatchSchemeDetail({ scid: state.parentId, scBelong: 0 }).then((res) => {
    if (res.code == 200) {
      console.log(res.data, '父级方案')
      let { models } = res.data
      let array = []
      models.info.forEach((item, index) => {
        array.push({ label: item.disTypeName, id: item.disType })
      })
      state.modelInfo = models.info
      state.modelType = array.filter(
        (item, index) => array.findIndex((i) => i.id === item.id) === index
      )
      state.diapatchMethods = state.modelType[0]?.id
      console.log(state.modelType, state.modelInfo, '志')
    }
  })
  await handleChangeSelect(state.modelType[0]?.id)
  //查询基本条件
  //  await getResvCondsList(state.scidIns)
  handleCurrentChangeSingle(state.singleTableData[0], 0)
  tableDataRef.value.setCurrentRow(state.singleTableData[0])
  // 编辑
  if (item.row.scid) {
    await getDetailData(item.row.scid)
  } else {
    // 新建
    state.schemeName = ''
    state.saveForm.id = ''
    console.log(state.singleTableData, '888')
    state.saveForm.reservoirs = []
    state.singleTableData.forEach((item) => {
      state.saveForm.reservoirs.push({
        ins: {},
        blkcd: item.blkcd,
        disType: item.disType,
        disMid: item.models[0].mid,
        disScid: item.models[0].schemes[0].id,
        optims: item.models[0].schemes[0].optims,
        rules: (item.models[0].schemes[0].rules = item.models[0].schemes[0].rules.map((child) => {
          let { id, ...obj } = child
          return { ...obj }
        })),
        conds: (item.models[0].schemes[0].conds = item.models[0].schemes[0].conds.map((child) => {
          let { id, ...obj } = child
          return { ...obj }
        })),
        // precipitations:[],
        trials: [],
        trialData: []
      })
    })
  }
  console.log(state.saveForm.reservoirs, '888')
}
// 获取水库调度详情
async function getDetailData(scid) {
  await resvDispatchDetail({ disScid: scid }).then(async (res) => {
    if (res.code === 200) {
      state.saveForm.id = res.data.id
      console.log(res.data, '查看id2')
      state.saveForm.reservoirs = res.data.reservoirs
      let arr = res.data.reservoirs
      state.schemeName = res.data.scName
      state.singleTableData.forEach((child, index) => {
        arr.forEach((e) => {
          // 如果水库相同
          if (child.blkcd == e.blkcd) {
            // 试算回显
            child.trialData = JSON.parse(JSON.stringify(e.trials))
            child.disType = e.disType
            child.models[0].schemes[0].id = e.disScid
            child.models[0].schemes[0].scName = e.disScName
            child.models[0].schemes[0].conds = e.conds
            child.models[0].schemes[0].precipitations = e.precipitations
            child.models[0].schemes[0].optims = e.optims
            child.models[0].schemes[0].rules = e.rules
            child.models[0].schemes[0].ins = e.ins
            child.models[0].mid = e.disMid
            child.models[0].modelName = e.disNm
          }
        })
      })
      await getResvCondsList(state.scidIns)
      handleCurrentChangeSingle(state.singleTableData[0], 0)
      tableDataRef.value.setCurrentRow(state.singleTableData[0])

      console.log('回显查看', state.singleTableData, state.saveForm)
    }
  })
}
// defineExpose({ handleOpenModal })

let contactDot
function filterTableData(data) {
  state.spanArr = []
  data.forEach((item, index) => {
    if (index == 0) {
      state.spanArr.push(1)
      contactDot = 0
    } else {
      if (item.rangeName == data[index - 1].rangeName) {
        state.spanArr[contactDot] += 1
        state.spanArr.push(0)
      } else {
        state.spanArr.push(1)
        contactDot = index
      }
    }
  })
  console.log('666', state.spanArr)
}
// 选择列表中某一行
function handleCurrentChangeSingle(item, index) {
  clearInterval(state.setInterValTimer)
  state.trialData = []
  state.jointTrialData = []
  state.showGoint = false
  if (item && item != -1 && item.engType == 0) {
    console.log(item, state.singleTableData, '水库')
    state.showGoint = false
    state.resultData = []
    state.blkcd = item.blkcd
    state.blknm = item.blknm
    state.currentName = state.blknm
    state.rowItem = item
    leftInfoRef.value.handleClickModel({
      blkcd: state.blkcd,
      blknm: state.blknm,
      singleData: state.singleTableData,
      parentId: state.parentId,
      scid: state.dispatchSchemeData.length && state.dispatchSchemeData[0].scid,
      waterId: state.zoneId,
      showGoint: state.showGoint,
      jointFlag: false,
      scidIns: state.scidIns
    })
    state.trialData = item.trialData
    // table.value.toggleAllSelection()
  } else if (item && item != -1 && item.engType == 1) {
    console.log(item, state.singleTableData, '水库')
    state.resultData = []
    state.blkcd = item.blkcd
    state.blknm = item.blknm
    state.currentName = state.blknm
    state.rowItem = item
    leftInfoRef.value.handleClickModel({
      blkcd: state.blkcd,
      blknm: state.blknm,
      singleData: state.singleTableData,
      parentId: state.parentId,
      scid: state.dispatchSchemeData.length && state.dispatchSchemeData[0].scid,
      waterId: state.zoneId,
      showGoint: state.showGoint,
      jointFlag: true,
      scidIns: state.scidIns
    })
    state.trialData = item.trialData
    state.jointTrialData = item.jointTrialData
    // jointTable.value.toggleAllSelection()
  } else if (item == -1) {
    state.showGoint = true
    let arr = state.saveForm.joints.filter((e) => {
      return e.rangeCode == index.rangeCode
    })
    console.log('arr', arr)
    state.jointTrialData = arr[0]?.jointTrialData
    // debugger
    // state.showGoint = true
    // state.trialData = item.trialData
    // state.jointTrialData = item.jointTrialData
    // jointTable.value.toggleAllSelection()
  }

  // handledDspatchRadio(item.reservoirsItem.disType)
  // handleChangeRuleDispatch(item.reservoirsItem.disMid)
  // handleChangeOptModel(item.reservoirsItem.disScid)
}
/**
 * 查询水库基本条件
 */
const getResvCondsList = (scid) => {
  return new Promise((resolve, reject) => {
    getResvConds({ scid: scid, blkcd: '' }).then((res) => {
      if (res.code === 200) {
        state.baseCondArr = res.data
        state.singleTableData.forEach((item, index) => {
          item.models[0].schemes[0].conds = state.baseCondArr.filter((c) => {
            return c.blkcd == item.blkcd
          })
        })
        resolve(state.singleTableData)
      }
    })
  })
}
//查看水库信息,合并数据
function ResvsList(id, rangeCodes = '') {
  return new Promise((resolve, reject) => {
    getDisResvs({ zoneId: id, scid: state.scidIns, rangeCodes: rangeCodes }).then((res) => {
      if (res.code === 200) {
        state.singleTableData = res.data
        filterTableData(state.singleTableData)
        state.singleTableData = state.singleTableData.map((item) => {
          return {
            ...item,
            disType: 1,
            trialData: [],
            jointTrialData: [],
            models: [
              {
                mid: 3,
                modelName: '',
                schemes: [
                  {
                    blkcd: '',
                    optims: [],
                    isPublish: 1,
                    rules: [],
                    conds: [],
                    ins: {}
                  }
                ]
              }
            ]
          }
        })
        resolve(state.singleTableData)
        console.log('22', state.singleTableData)
      }
    })
  })
}
// const emit = defineEmits(["handleRefresh"]);
// emit("handleRefresh");
//表单合并单元格
// 通用行合并函数（将相同多列数据合并为一行）
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0) {
    const _row = state.spanArr[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col
    }
  }
}
function cellMerge({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0 || columnIndex === 1) {
    //这里判断第几列需要合并
    let item = state.mergerItems.find((item) => item.columnIndex === columnIndex)
    const _row = item.spanArr[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col
    }
  }
}

// 关闭弹框的回调

//详情弹框
function handleDetialDialog() {
  let tId = []
  let arrResult = []
  let flag = true
  let obj = {}
  state.resultData = state.resultData.reduce((cur, next) => {
    obj[next.trialId] ? '' : (obj[next.trialId] = true && cur.push(next))
    return cur
  }, [])
  // 如果没有选中方案就提示
  if (!state.ssList.length) {
    ElMessage.warning('请先选择要查看的方案')
  } else {
    // 如果选中了 就判断
    //遍历选中的方案中是否全部存在结果 result
    state.ssList.forEach((a) => {
      if (!(a?.result && a.result.length)) {
        flag = false
      }
    })
    // 如果全部存在
    if (flag) {
      // 获取选中的列表的每一个的试算id
      state.ssList.forEach((e) => tId.push(e.trialId))
      arrResult = state.resultData.filter((e) => tId.includes(e.trialId))
      if (arrResult.length > 4) {
        ElMessage.warning('最多选择四个方案')
        return false
      }
      showDetailsRef.value.handleOpenDetails({ result: arrResult, trialList: state.ssList })
    } else {
      ElMessageBox.confirm(`当前选择的方案中存在未进行试算的方案，是否进行试算`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 试算函数
          handleClickTryComput()
        })
        .catch(() => {})
    }
  }
}
//联合详情弹框
function handleJointDetialDialog() {
  let tId = []
  let arrResult = []
  let flag = true
  // 如果没有选中方案就提示
  if (!state.jointSsList.length) {
    ElMessage.warning('请先选择要查看的方案')
  } else {
    // 如果选中了 就判断
    //遍历选中的方案中是否全部存在结果 result
    flag = state.jointSsList.every((i) => {
      return i.status == 2
    })

    // 如果全部存在
    if (flag) {
      // 获取选中的列表的每一个的试算id
      state.jointSsList.forEach((e) => tId.push(e.trialId))
      // arrResult = state.resultData.filter((e) => tId.includes(e.trialId))
      jointResultRef.value.handleOpenDetails({
        baseScheme: state.dispatchSchemeData,
        rangeCode: state.rangeCode,
        zoneId: state.zoneId,
        trialList: state.jointSsList
      })
    } else {
      ElMessageBox.confirm(`当前选择的方案中存在未进行试算的方案，是否进行试算`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 试算函数
          handleClickTryComputJoint()
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="less">
.el-table-filter__list {
  .el-table-filter__list-item {
    &:nth-of-type(1) {
      display: none;
    }
  }
}
.el-dialog.my-dialog {
  .el-dialog__body {
    padding: 5px 20px !important;
  }
}
</style>
<style lang="less" scoped>
.status {
  color: gray;
  &.success {
    color: green;
  }
  &.fail {
    color: red;
  }
}
.boder-div-box {
  height: 100%;
  width: 100%;
  overflow-y: auto;
}
.dialog-container {
  display: flex;
  height: 500px;
  width: 100%;

  .left-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 380px;
    height: 100%;
    // margin-right: 10px;
    // border: 1px solid;
    .plan-name-box {
      padding: 0 20px;
      box-sizing: border-box;
      display: flex;
      height: 30px;
      width: 100%;
      // background-color: rebeccapurple;
      .plan-font {
        color: #545252d7;

        white-space: nowrap;
        padding: 0 10px;
        line-height: 30px;
        font-size: 15px;
      }
    }
    .tabs-box {
      height: calc(100% - 50px);
      width: 100%;
      padding: 0 10px;
      box-sizing: border-box;
      margin-top: 20px;
      // background-color: red;
      .demo-tabs {
        height: 100%;
        :deep(.el-tabs__header) {
          margin: 0px;
          display: none;
        }
        :deep(.el-tabs__content) {
          height: calc(100% - 50px);
          // padding: 10px;
          .el-tab-pane {
            height: 100%;
            // height: calc(100% - 10px);
            .first-input {
              width: 100%;
              height: 40px;
              // background-color: royalblue;
            }
            .first-table {
              height: calc(100% - 100px);
              width: 100%;

              // background-color: #4fc0f1;
              .single-table {
                height: 100%;
                .el-table__inner-wrapper {
                  .el-table__body-wrapper {
                    .el-scrollbar {
                      .el-scrollbar__wrap {
                        .el-scrollbar__view {
                          // height: 20px;
                          .el-table__body {
                            tbody {
                              .el-table__row {
                                cursor: pointer;
                                &.current-row {
                                  color: #409eff;
                                  font-weight: 500;
                                  font-size: 16px;
                                  .cell-bg {
                                    // background: red;
                                    // color: #545252d7;
                                  }
                                }
                                &.row-bg {
                                  background: rgba(238, 245, 251);
                                  .cell-bg {
                                    // background: red;
                                    color: #545252d7;
                                  }
                                }
                              }
                            }
                          }
                          // .el-table__body {
                          //   height: 100px;
                          // }
                        }
                      }
                    }
                  }
                }
                .iconfont {
                  &.active {
                    color: #409eff;
                    font-weight: 700;
                  }
                }
                .engType-name-two {
                  &.joint {
                    color: blue;
                  }
                }
                .engType-name {
                  color: #606266;

                  &.active {
                    color: #409eff;
                    font-weight: 700;
                  }
                }
                // :deep(.el-table__row) {
                //   cursor: pointer;
                // }
              }
            }
            .first-select {
              margin-top: 30px;
              display: flex;
              align-items: center;
              height: 30px;
              width: 100%;
              // background-color: teal;
              .plan-font1 {
                color: #545252d7;
                white-space: nowrap;
                padding: 0 10px;
                line-height: 30px;
                font-size: 15px;
              }
              .switch-right {
                margin-left: 20px;
              }
            }
            .first-bottom-btn {
              margin-top: 15px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
              height: 40px;
              padding: 0 10px;
              box-sizing: border-box;
            }
          }
        }
      }
      .demo-tabs1 {
        :deep(.el-tabs__content) {
          padding: 5px;
        }
      }

      // .warehouseType-box {
      //   display: flex;
      //   width: 100%;
      //   height: 50px;
      //   // background-color: royalblue;
      //   .base-box {
      //     font-size: 18px;
      //     font-weight: 600;
      //     line-height: 50px;
      //     text-align: center;
      //     height: 100%;
      //     width: 50%;
      //   }
      // }
    }
  }
  .right-box {
    display: flex;
    width: calc(100% - 400px);
    height: 100%;
    flex-direction: column;
    .concept-box {
      display: flex;
      justify-content: space-between;
      .title {
        font-size: 18px;
      }
    }

    // background-color: #4fc0f1;

    .reservoir-info {
      width: 100%;
      flex: 1;
      // height: calc(100% - 30px);
      // height: auto;
      height: calc(100% - 230px);

      .reservoir-name {
        height: 48px;
        width: 100%;
        line-height: 60px;
        font-size: 15px;
        font-weight: 600;
        color: #409eff;
        text-align: center;
      }
      .info-body {
        display: flex;
        height: calc(100% - 48px);
        width: 100%;
      }
      .el-table {
        height: 100%;
      }
      .left-info {
        // width: 750px;
        width: calc(100% - 20px);
        height: 100%;
        margin-right: 10px;
        box-sizing: border-box;
        // border: 1px solid #7b7979d7;
      }
      .middle-info {
        display: none;
        // width: calc(100% - 500px);
        // box-sizing: border-box;
        // border: 1px solid #dcdfe6;
        // border-right: 0px;
        // height: calc(100% - 60px);
        // margin-right: 0px;
      }
      .right-info {
        width: calc(100% - 870px);
        flex: 1;
        .el-table {
          box-sizing: border-box;
          border: 1px solid #dcdfe6;
          height: calc(100% - 60px);
        }
        .detail-box {
          display: flex;
          justify-content: center;
          white-space: nowrap;
        }

        .right-info-btn {
          width: 100%;
          height: 60px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
        }
      }
    }
  }
}
</style>

